
let Vue;

const forEach = (obj, callback) => {
	Object.keys(obj).forEach(key => {
		callback(key, obj[key])
	})
}


class Store {
	// 构造函数传入配置项
	constructor(options) {
		this._s = new Vue({
			data: {
				state: options.state
			}
		});
		// 得到配置上的getters，如果没有写就默认为空
		let getters = options.getters || {};
		this.getters = {}
		forEach(getters, (key, value) => {
			Object.defineProperty(this.getters, key, {
				get: () => {
					return value(this.state)
				}
			})
		})

		// 获取mutation配置
		let mutations = options.mutations || {};
		this.mutations = {};

		forEach(mutations, (key, value) => {
			this.mutations[key] = (payload) => {
				value(this.state, payload)
			}
		})

		// 获取配置的actions，进行对actions的修改
		let actions = options.actions || {};
		this.actions = {};

		forEach(actions, (key, value) => {
			this.actions[key] = (payload) => {
				value(this, payload)
			}
		})







	}
	dispatch (type, payload) {
		this.actions[type](payload)
	}
	commit (type, payload) {
		this.mutations[type](payload)
	}
	get state () {
		return this._s.state;
	}
}


function install (v) {
	// 获取Vue框架
	Vue = v;
	// 通过全局的混入方法，将在所有组件进行数据实例化之前，绑定$store
	Vue.mixin({
		beforeCreate () {
			// 判断是否是根组件
			if (this.$options && this.$options.store) {
				this.$store = this.$options.store;
			} else {
				this.$store = this.$parent && this.$parent.$store;
			}
		}
	})
}


export default {
	install,
	Store
}